// For hidden process
var canvasDivHidden = document.getElementById('canvasHidden');
canvasHidden = document.createElement('canvas');
canvasHidden.setAttribute('width', canvasWidth);
canvasHidden.setAttribute('height', canvasHeight);
canvasHidden.setAttribute('id', 'canvasHidden');
canvasDivHidden.appendChild(canvasHidden);
if(typeof G_vmlCanvasManager != 'undefined') {
	canvasHidden = G_vmlCanvasManager.initElement(canvasHidden);
}
contextHidden = canvasHidden.getContext("2d"); // Grab the 2d canvas context
// For hidden process


var current_shape = -1;
var drag_shape = false;
var choose_shape = '';
var insert_image = false;
var resize_shape = -1;
var move_shape = -1;
var current_move_shape = -1;
var stage = new Kinetic.Stage({
    container: 'canvasDiv2',
    width: canvasWidth,
    height: canvasHeight
  });
var mouseSX, mouseSY, mouseDX, mouseDY;
var layer = new Kinetic.Layer();
var mode_shape = '';
var resizeX, resizeY, moveX, moveY, resizing, moving, rotateX, rotateY, rotating, rotateCX, rotateCY;
var current_tool_shape = '';
var img_shape = Array();
var text_shape = Array();
var font_shape = Array();
var color_shape = Array();
var fontsize_shape = Array();
var mask_shape = Array();
var maskm_shape = Array();
var maskb_shape = Array();
var tempImg_shape = Array();
var moveImg_shape = Array();
// add the layer to the stage
stage.add(layer);

function drawshape(finished){
	if(mode_shape=='') return;

      layer.add(draw_shape);
      layer.draw();

      var shape = layer.get('Shape')[current_shape];
      if(finished==false) shape.remove();
      else{
	      event_shape(draw_shape);
      }
}
function event_shape(draw_shape){
	draw_shape.on('mouseover', function() {
        document.body.style.cursor = 'pointer';
      });
      draw_shape.on('mouseout', function() {
        document.body.style.cursor = 'default';
      });
      draw_shape.on('mousedown', function(e) {
        choose_shape = $(this).context.attrs.name;
		this.moveToTop();
        if(resize_shape!=-1){
        	rotateX = resizeX = e.pageX;
			rotateY = resizeY = e.pageY;
			resizing = true;
        }
        if(move_shape!=-1){
        	moveX = e.pageX;
			moveY = e.pageY;
			moving = true;
        }
        if(resize_shape==9){
			rotating = this.attrs.shapeRotate;
        	rotateCX = this.attrs.shapeX + this.attrs.shapeW/2 + $(this).context.attrs.x;
        	rotateCY = this.attrs.shapeY + this.attrs.shapeH/2 + $(this).context.attrs.y;
        }
      });
      draw_shape.on('mouseup', function() {
        if(resize_shape!=-1){
			resizing = false;
        }
        if(move_shape!=-1){
			moving = false;
        }
        if(text_shape[choose_shape]!=undefined) {
        	var font = '';
        	var color = $('.color span[data='+color_shape[choose_shape]+']').attr('class').replace('active','');
        	if(font_shape[choose_shape]=='UTMFleur') font = 'font-1';
		    if(font_shape[choose_shape]=='UTMAquarelle') font = 'font-2';
		    if(font_shape[choose_shape]=='UTMEdwardianKT') font = 'font-3';
		    if(font_shape[choose_shape]=='UTMEdwardianB') font = 'font-4';
		    if(font_shape[choose_shape]=='UVNSangSong') font = 'font-5';
        	$('.font-size').val(fontsize_shape[choose_shape]);
        	$('.input-text textarea').val(text_shape[choose_shape]);
        	$('.input-text textarea').attr('class', color+' '+font);
        	$('.tt-toolbar .color span').removeClass('active');
        	$('.'+color).addClass('active');
        	$('.tt-toolbar .font').removeClass('active');
        	$('.'+font).addClass('active');
        	$('.font').parent().attr('class', 't'+$('.'+color).attr('class').replace('active',''));
        }

      });
      draw_shape.on('dblclick', function() {
        if(text_shape[choose_shape]!=undefined){
        	$('.input-text').addClass('active');
            $('.input-text').fadeIn();
        }
      });
       draw_shape.on('mousemove', function() {
        check_resize();
        if(resize_shape==1) document.body.style.cursor = 'nw-resize';
        else if(resize_shape==2) document.body.style.cursor = 'n-resize';
        else if(resize_shape==3) document.body.style.cursor = 'ne-resize';
        else if(resize_shape==4) document.body.style.cursor = 'e-resize';
        else if(resize_shape==5) document.body.style.cursor = 'nw-resize';
        else if(resize_shape==6) document.body.style.cursor = 'n-resize';
        else if(resize_shape==7) document.body.style.cursor = 'ne-resize';
        else if(resize_shape==8) document.body.style.cursor = 'e-resize';
        else if(resize_shape==9) document.body.style.cursor = 'move';
        else if(move_shape==1) document.body.style.cursor = 'move';
        else document.body.style.cursor = 'pointer';

      });
      draw_shape.on('dragmove', function(e) {
        if(choose_shape!='' && resizing==true) {
	        var mouseRX = e.pageX;
	        var mouseRY = e.pageY;

	        if(resize_shape==1){
	        	$(this).context.attrs.shapeW -= mouseRX- resizeX;
	        	$(this).context.attrs.shapeH -= mouseRY- resizeY;
	        }
	        if(resize_shape==2){
	        	$(this).context.attrs.shapeX -= mouseRX- resizeX;
	        	$(this).context.attrs.shapeH -= mouseRY- resizeY;
	        }
	        if(resize_shape==3){
	        	$(this).context.attrs.shapeX -= mouseRX- resizeX;
	        	$(this).context.attrs.shapeW += mouseRX- resizeX;
	        	$(this).context.attrs.shapeH -= mouseRY- resizeY;
	        }
	        if(resize_shape==4){
	        	$(this).context.attrs.shapeX -= mouseRX- resizeX;
	        	$(this).context.attrs.shapeY -= mouseRY- resizeY;
	        	$(this).context.attrs.shapeW += mouseRX- resizeX;
	        }
	        if(resize_shape==5){
	        	$(this).context.attrs.shapeX -= mouseRX- resizeX;
	        	$(this).context.attrs.shapeY -= mouseRY- resizeY; 
	        	$(this).context.attrs.shapeW += mouseRX- resizeX;
	        	$(this).context.attrs.shapeH += mouseRY- resizeY;
	        }
	        if(resize_shape==6){
	        	$(this).context.attrs.shapeX -= mouseRX- resizeX;
	        	$(this).context.attrs.shapeY -= mouseRY- resizeY;
	        	$(this).context.attrs.shapeH += mouseRY- resizeY;
	        }
	        if(resize_shape==7){
	        	$(this).context.attrs.shapeY -= mouseRY- resizeY;
	        	$(this).context.attrs.shapeW -= mouseRX- resizeX;
	        	$(this).context.attrs.shapeH += mouseRY- resizeY;
	        }
	        if(resize_shape==8){
	        	$(this).context.attrs.shapeY -= mouseRY- resizeY;
	        	$(this).context.attrs.shapeW -= mouseRX- resizeX;
	        }
	        if(resize_shape==9){
	        	var offsetRotateX = - $('#canvas')[0].offsetLeft - $('.container')[0].offsetLeft;
	        	var offsetRotateY = - $('#canvas')[0].offsetTop;
	        	$(this).context.attrs.shapeX -= mouseRX- resizeX;
	        	$(this).context.attrs.shapeY -= mouseRY- resizeY; 
	        	var _x1 = rotateX+offsetRotateX, _x2 = rotateCX, _x = mouseRX+offsetRotateX, _y1 = rotateY+offsetRotateY, _y2 = rotateCY, _y = mouseRY+offsetRotateY;
	        	var sideRotate = _x*(_y2-_y1)-_x1*(_y2-_y1)-_y*(_x2-_x1)+_y1*(_x2-_x1);
	        	if(sideRotate>=0){
	        		$(this).context.attrs.shapeRotate = rotating + find_angle({x:rotateX+offsetRotateX,y:rotateY+offsetRotateY},{x:mouseRX+offsetRotateX,y:mouseRY+offsetRotateY},{x:rotateCX,y:rotateCY})*180/Math.PI;
	        	}else{
	        		$(this).context.attrs.shapeRotate = rotating - find_angle({x:rotateX+offsetRotateX,y:rotateY+offsetRotateY},{x:mouseRX+offsetRotateX,y:mouseRY+offsetRotateY},{x:rotateCX,y:rotateCY})*180/Math.PI;
	        	}
	        }
        	resizeX = e.pageX;
			resizeY = e.pageY;
	    }
		
        if(choose_shape!='' && moving==true) {
	        var mouseRX = e.pageX;
	        var mouseRY = e.pageY;

	        if(move_shape==1){
	        	$(this).context.attrs.shapeX -= mouseRX- moveX;
	        	$(this).context.attrs.shapeY -= mouseRY- moveY; 

	        	imgtemp = tempImg_shape[this.attrs.name];
	        	current_move_shape = imgtemp.current_move_shape;

	        	moveImg_shape[current_move_shape].osX += mouseRX- moveX;
	        	moveImg_shape[current_move_shape].osY += mouseRY- moveY;

				img = moveImg_shape[current_move_shape].img; 
				mask = moveImg_shape[current_move_shape].mask; 
				maskm = moveImg_shape[current_move_shape].maskm; 
				maskb = moveImg_shape[current_move_shape].maskb; 
				shapeW = moveImg_shape[current_move_shape].shapeW; 
				shapeH = moveImg_shape[current_move_shape].shapeH; 
				osX = moveImg_shape[current_move_shape].osX; 
				osY = moveImg_shape[current_move_shape].osY; 
	        	var maskWidth = mask.width;
				var maskHeight = mask.height;
				var img_width = img.width;
				var img_height = img.height;
				var offsetX = 0;
				var offsetY = 0;
				if(img.width!=maskWidth || img.height!=maskHeight){
					var radio_img_w = img.width / maskWidth;
					var radio_img_h = img.height / maskHeight;
					if(radio_img_w < radio_img_h){
						img_width = maskWidth;
						img_height = img.height / radio_img_w;
						offsetY = -(img_height - maskHeight)/2;
					}else{
						img_height = maskHeight;
						img_width = img.width / radio_img_h;
						offsetX = -(img_width - maskWidth)/2;
					}
				}
				offsetX += osX;
				offsetY += osY;
				canvasHidden.setAttribute('width', maskWidth);
				canvasHidden.setAttribute('height', maskHeight);
				contextHidden.clearRect(0, 0, maskWidth, maskHeight);
				contextHidden.drawImage(maskm, 0, 0, maskWidth, maskHeight);
				contextHidden.globalCompositeOperation = 'source-in';
				contextHidden.drawImage(img, offsetX, offsetY, img_width, img_height);
				contextHidden.globalCompositeOperation = 'source-over';
				contextHidden.drawImage(maskb, 0, 0, maskWidth, maskHeight);
				var maskLayerData = contextHidden.getImageData(0, 0, maskWidth, maskHeight);
				var imgtemp = document.createElement("img");
				imgtemp.src = canvasHidden.toDataURL("image/png");
				imgtemp.current_move_shape = current_move_shape;
				var curname = this.attrs.name;
				imgtemp.onload = function() {
	                tempImg_shape[curname] = imgtemp;
	            }
	        }
        	moveX = e.pageX;
			moveY = e.pageY;
	    }
		/*if(this.attrs.x+this.attrs.shapeOW > canvasWidth - padding[1]){	
            this.attrs.x = canvasWidth - padding[1]-this.attrs.shapeOW;
	    }
		if(this.attrs.x+this.attrs.shapeOW-this.attrs.shapeW < padding[3]){	
            this.attrs.x = padding[3]-this.attrs.shapeOW+this.attrs.shapeOW;
	    }
		if(this.attrs.y+this.attrs.shapeOH > canvasHeight - padding[2]){	
            this.attrs.y = canvasHeight - padding[2]-this.attrs.shapeOH;
	    }
		if(this.attrs.y+this.attrs.shapeOH-this.attrs.shapeH < padding[0]){	
            this.attrs.y = padding[0]-this.attrs.shapeOH+this.attrs.shapeH;
	    }*/
		
		if(this.attrs.x+this.attrs.shapeX+this.attrs.shapeW > canvasWidth - padding[1]){	
            this.attrs.x = canvasWidth - padding[1]-this.attrs.shapeW-this.attrs.shapeX;
	    }
		if(this.attrs.x+this.attrs.shapeX < padding[3]){	
            this.attrs.x = padding[3]-this.attrs.shapeX;
	    }
		if(this.attrs.y+this.attrs.shapeY+this.attrs.shapeH > canvasHeight - padding[2]){	
            this.attrs.y = canvasHeight - padding[2]-this.attrs.shapeH-this.attrs.shapeY;
	    }
		if(this.attrs.y+this.attrs.shapeY < padding[0]){	
            this.attrs.y = padding[0]-this.attrs.shapeY;
	    }
		
      });
}
function find_angle(p0,p1,c) {
    var p0c = Math.sqrt(Math.pow(c.x-p0.x,2)+
                        Math.pow(c.y-p0.y,2)); // p0->c (b)   
    var p1c = Math.sqrt(Math.pow(c.x-p1.x,2)+
                        Math.pow(c.y-p1.y,2)); // p1->c (a)
    var p0p1 = Math.sqrt(Math.pow(p1.x-p0.x,2)+
                         Math.pow(p1.y-p0.y,2)); // p0->p1 (c)
    return Math.acos((p1c*p1c+p0c*p0c-p0p1*p0p1)/(2*p1c*p0c));
}
function draw_insert_image(img){
	// if(choose_shape==''){
		var img_width = img.width;
		var img_height = img.height;
		if(img.width>=600 || img.height>=400){
			var radio_img_w = img.width / 480;
			var radio_img_h = img.height / 360;
			if(radio_img_w > radio_img_h){
				img_width = 480;
				img_height = img.height / radio_img_w;
			}else{
				img_height = 360;
				img_width = img.width / radio_img_h;
			}
		}
	  	var draw_shape = new Kinetic.Shape({
		    drawFunc: function(canvas) {
		    	var shapeX = this.attrs.shapeX;
		    	var shapeY = this.attrs.shapeY;
		    	var shapeH = this.attrs.shapeH;
		    	var shapeW = this.attrs.shapeW;

		        var context = canvas.getContext();

		        context.translate(shapeX+shapeW/2, shapeY+shapeH/2);
	        	context.rotate(this.attrs.shapeRotate*Math.PI/180);

			    context.beginPath();
			    context.rect(-shapeW/2, -shapeH/2, shapeW, shapeH);
			    this.attrs.fill = this.attrs.fillShape;
			    canvas.fillStroke(this);
			    context.closePath();

			    context.beginPath(); 
			    context.rect(-shapeW/2, -shapeH/2, shapeW, shapeH);
			    context.drawImage(img, -shapeW/2, -shapeH/2, shapeW, shapeH);
			    this.attrs.fill = null;
			    context.closePath();
			    canvas.fillStroke(this);

				if(choose_shape!=''&&this.attrs.name==choose_shape) {
			        var old_stroke = this.attrs.stroke;
			        var old_strokeWidth = this.attrs.strokeWidth;
			        var old_fill = this.attrs.fill;
					draw_selection(context, canvas, this);
					this.attrs.stroke = old_stroke;
		    		this.attrs.strokeWidth = old_strokeWidth;
		    		this.attrs.fill = old_fill;
				}

				context.rotate((360-this.attrs.shapeRotate)*Math.PI/180);
		    	context.translate(-(shapeX+shapeW/2), -(shapeY+shapeH/2));
		    },
		    shapeRotate: 0,
		    fillShape: '',
		    stroke: '',
		    strokeWidth: '',
	        draggable: true,
	        shapeX: 0,
	        shapeY: 0,
	        shapeW: img_width,
	        shapeH: img_height,
	        shapeOW: img_width,
	        shapeOH: img_height,
	        x: (canvasWidth/2-img_width/2),
	        y: (canvasHeight/2-img_height/2),
	        fillPatternOffsetX: -220,
	        fillPatternOffsetY: 70,
	        name : "chentrangtri-" + current_shape,
		});

		layer.add(draw_shape);
	    layer.draw();
	    event_shape(draw_shape);
	    current_shape++;
		editing = true;
	// }else{
	// 	img_shape[choose_shape] = img;
	// 	layer.draw();
	// }
}
function draw_text(text,font,color,font_size){
	if(choose_shape==''){
		var img_width = $('.input-text textarea').width();
		var img_height = $('.input-text textarea').height();
		if($('.input-text textarea').width()>=600 || $('.input-text textarea').height()>=400){
			var radio_img_w = $('.input-text textarea').width() / 480;
			var radio_img_h = $('.input-text textarea').height() / 360;
			if(radio_img_w > radio_img_h){
				img_width = 480;
				img_height = $('.input-text textarea').height() / radio_img_w;
			}else{
				img_height = 360;
				img_width = $('.input-text textarea').width() / radio_img_h;
			}
		}
		text_shape["chenchu-" + current_shape] = text;
		font_shape["chenchu-" + current_shape] = font;
		color_shape["chenchu-" + current_shape] = color;
		fontsize_shape["chenchu-" + current_shape] = font_size;
						
	  	var draw_shape = new Kinetic.Shape({
		    drawFunc: function(canvas) {
		    	var shapeX = this.attrs.shapeX;
		    	var shapeY = this.attrs.shapeY;
		    	var shapeH = this.attrs.shapeH;
		    	var shapeW = this.attrs.shapeW;

		        var context = canvas.getContext();

		        context.translate(shapeX+shapeW/2, shapeY+shapeH/2);
	        	context.rotate(this.attrs.shapeRotate*Math.PI/180);

			    context.beginPath();
			    context.rect(-shapeW/2, -shapeH/2, shapeW, shapeH);
			    this.attrs.fill = this.attrs.fillShape;
			    canvas.fillStroke(this);
			    context.closePath();

			    context.beginPath(); 
			    context.rect(-shapeW/2, -shapeH/2, shapeW, shapeH);
			    var y = 0;
			    if(text_shape[this.attrs.name]!=undefined) {
			    	var lines = text_shape[this.attrs.name].split('\n');
			    	for(var i = 0; i < lines.length; i++) {
	      				var words = lines[i].split(' ');
				        var line = '';
						//var font_size = (this.attrs.shapeW/this.attrs.shapeOW)*26;
				        lineHeight = 35;
				        maxWidth = shapeW;
	      				context.lineWidth = 1;
				    	context.font = 'normal '+fontsize_shape[this.attrs.name]+'px '+font_shape[this.attrs.name];
				    	context.fillStyle = color_shape[this.attrs.name];
				    	context.strokeStyle = 'white';
				        for(var n = 0; n < words.length; n++) {
				          var testLine = line + words[n] + ' ';
				          var metrics = context.measureText(testLine);
				          var testWidth = metrics.width;
				          if (testWidth > maxWidth && n > 0) {
		      				context.strokeText(line, -shapeW/2, y - (shapeH/2-fontsize_shape[this.attrs.name]));
					    	context.fillText(line, -shapeW/2, y - (shapeH/2-fontsize_shape[this.attrs.name]));
				            line = words[n] + ' ';
				            y += lineHeight;
				          }
				          else {
				            line = testLine;
				          }
				        }
	        			context.strokeText(line, -shapeW/2, y - (shapeH/2-26));
	        			context.fillText(line, -shapeW/2, y - (shapeH/2-26));
				        y += lineHeight;

	        			/*if(choose_shape==''){
	        				var tempLine = lines[i];
					        var tempmetrics = context.measureText(tempLine);
					        var tempWidth = tempmetrics.width;
				        	if(this.attrs.shapeW > tempWidth) this.attrs.shapeW = this.attrs.shapeOW = tempWidth+26;
				        	this.attrs.shapeH = this.attrs.shapeOH = y;
	        			}*/
				    }
			    }
			    this.attrs.fill = null;
			    context.closePath();
			    canvas.fillStroke(this);

				if(choose_shape!=''&&this.attrs.name==choose_shape) {
			        var old_stroke = this.attrs.stroke;
			        var old_strokeWidth = this.attrs.strokeWidth;
			        var old_fill = this.attrs.fill;
					draw_selection(context, canvas, this);
					this.attrs.stroke = old_stroke;
		    		this.attrs.strokeWidth = old_strokeWidth;
		    		this.attrs.fill = old_fill;
				}

				context.rotate((360-this.attrs.shapeRotate)*Math.PI/180);
		    	context.translate(-(shapeX+shapeW/2), -(shapeY+shapeH/2));
		    },
		    shapeRotate: 0,
		    fillShape: '',
		    stroke: '',
		    strokeWidth: '',
	        draggable: true,
	        shapeX: 0,
	        shapeY: 0,
	        shapeW: img_width,
	        shapeH: img_height,
	        shapeOW: img_width,
	        shapeOH: img_height,
	        x: (canvasWidth/2-img_width/2),
	        y: (canvasHeight/2-img_height/2),
	        fillPatternOffsetX: -220,
	        fillPatternOffsetY: 70,
	        name : "chenchu-" + current_shape,
		});
		layer.add(draw_shape);
	    layer.draw();
	    event_shape(draw_shape);
	    current_shape++;
		editing = true;
	}else{
		text_shape[choose_shape] = text;
		font_shape[choose_shape] = font;
		color_shape[choose_shape] = color;
		fontsize_shape[choose_shape] = font_size;
		layer.draw();
	}
}
function merge_mask(img,mask,maskm,maskb,shapeW,shapeH){
	current_move_shape++;
	var maskWidth = mask.width;
	var maskHeight = mask.height;
	var img_width = img.width;
	var img_height = img.height;
	var offsetX = 0;
	var offsetY = 0;
	if(img.width!=maskWidth || img.height!=maskHeight){
		var radio_img_w = img.width / maskWidth;
		var radio_img_h = img.height / maskHeight;
		if(radio_img_w < radio_img_h){
			img_width = maskWidth;
			img_height = img.height / radio_img_w;
			offsetY = -(img_height - maskHeight)/2;
		}else{
			img_height = maskHeight;
			img_width = img.width / radio_img_h;
			offsetX = -(img_width - maskWidth)/2;
		}
	}
	canvasHidden.setAttribute('width', maskWidth);
	canvasHidden.setAttribute('height', maskHeight);
	contextHidden.clearRect(0, 0, maskWidth, maskHeight);
	contextHidden.drawImage(maskm, 0, 0, maskWidth, maskHeight);
	contextHidden.globalCompositeOperation = 'source-in';
	contextHidden.drawImage(img, offsetX, offsetY, img_width, img_height);
	contextHidden.globalCompositeOperation = 'source-over';
	contextHidden.drawImage(maskb, 0, 0, maskWidth, maskHeight);
	var maskLayerData = contextHidden.getImageData(0, 0, maskWidth, maskHeight);
	var imgtemp = document.createElement("img");
	imgtemp.src = canvasHidden.toDataURL("image/png");
	imgtemp.current_move_shape = current_move_shape;
	moveImg_shape[current_move_shape] = Object();
	moveImg_shape[current_move_shape].img = img; 
	moveImg_shape[current_move_shape].mask = mask; 
	moveImg_shape[current_move_shape].maskm = maskm; 
	moveImg_shape[current_move_shape].maskb = maskb; 
	moveImg_shape[current_move_shape].shapeW = shapeW; 
	moveImg_shape[current_move_shape].shapeH = shapeH; 
	moveImg_shape[current_move_shape].osX = 0; 
	moveImg_shape[current_move_shape].osY = 0; 
	return imgtemp;
}
function draw_mask_image(img,mask,maskm,maskb,tempImg){
	if(choose_shape==''){
		var img_width = mask.width;
		var img_height = mask.height;

		img_shape["chenhinh-" + current_shape] = img;
		mask_shape["chenhinh-" + current_shape] = mask;
		maskm_shape["chenhinh-" + current_shape] = maskm;
		maskb_shape["chenhinh-" + current_shape] = maskb;
		tempImg_shape["chenhinh-" + current_shape] = tempImg;
		
	  	var draw_shape = new Kinetic.Shape({
		    drawFunc: function(canvas) {
		    	var shapeX = this.attrs.shapeX;
		    	var shapeY = this.attrs.shapeY;
		    	var shapeH = this.attrs.shapeH;
		    	var shapeW = this.attrs.shapeW;

		        var context = canvas.getContext();

		        context.translate(shapeX+shapeW/2, shapeY+shapeH/2);
	        	context.rotate(this.attrs.shapeRotate*Math.PI/180);

			    context.beginPath();
			    context.rect(-shapeW/2, -shapeH/2, shapeW, shapeH);
			    this.attrs.fill = this.attrs.fillShape;
			    canvas.fillStroke(this);
			    context.closePath();

			    context.beginPath(); 
			    context.rect(-shapeW/2, -shapeH/2, shapeW, shapeH);
			    context.drawImage(tempImg_shape[this.attrs.name], -shapeW/2, -shapeH/2, shapeW, shapeH);
			    this.attrs.fill = null;
			    context.closePath();
			    canvas.fillStroke(this);
			    

				if(choose_shape!=''&&this.attrs.name==choose_shape) {
			        var old_stroke = this.attrs.stroke;
			        var old_strokeWidth = this.attrs.strokeWidth;
			        var old_fill = this.attrs.fill;
					draw_selection(context, canvas, this);
					this.attrs.stroke = old_stroke;
		    		this.attrs.strokeWidth = old_strokeWidth;
		    		this.attrs.fill = old_fill;
				}

				context.rotate((360-this.attrs.shapeRotate)*Math.PI/180);
		    	context.translate(-(shapeX+shapeW/2), -(shapeY+shapeH/2));
		    },
		    shapeRotate: 0,
		    fillShape: '',
		    stroke: '',
		    strokeWidth: '',
	        draggable: true,
	        shapeX: 0,
	        shapeY: 0,
	        shapeW: img_width,
	        shapeH: img_height,
	        shapeOW: img_width,
	        shapeOH: img_height,
	        x: (canvasWidth/2-img_width/2),
	        y: (canvasHeight/2-img_height/2),
	        fillPatternOffsetX: -220,
	        fillPatternOffsetY: 70,
	        name : "chenhinh-" + current_shape,
		});

		layer.add(draw_shape);
	    layer.draw();
	    event_shape(draw_shape);
	    current_shape++;
		editing = true;
	}
	// }else{
	// 	mask_shape[choose_shape] = mask;
	// 	img_shape[choose_shape] = img;
	// 	layer.draw();
	// }
}
function draw_selection(context, canvas, ele){
	var shape = layer.get('.'+choose_shape)[0];
	var x,y,w,h;
	
	x = -shape.attrs.shapeW/2;
	y = -shape.attrs.shapeH/2;
	w = shape.attrs.shapeW;
	h = shape.attrs.shapeH;

    ele.attrs.stroke = '#333333';
    ele.attrs.strokeWidth = 1;

    context.beginPath();
    context.rect(x-5, y-5, 10, 10);
    context.closePath();
    ele.attrs.fill = '#fffff1';
    canvas.fillStroke(ele);

    context.beginPath();
    context.rect(x-5+w/2, y-5, 10, 10);
    context.closePath();
    ele.attrs.fill = '#fffff2';
    canvas.fillStroke(ele);

    context.beginPath();
    context.rect(x-5+w, y-5, 10, 10);
    context.closePath();
    ele.attrs.fill = '#fffff3';
    canvas.fillStroke(ele);

    context.beginPath();
    context.rect(x-5+w, y-5+h/2, 10, 10);
    context.closePath();
    ele.attrs.fill = '#fffff4';
    canvas.fillStroke(ele);

    context.beginPath();
    context.rect(x-5+w, y-5+h, 10, 10);
    context.closePath();
    ele.attrs.fill = '#fffff5';
    canvas.fillStroke(ele);

    context.beginPath();
    context.rect(x-5+w/2, y-5+h, 10, 10);
    context.closePath();
    ele.attrs.fill = '#fffff6';
    canvas.fillStroke(ele);

    context.beginPath();
    context.rect(x-5, y-5+h, 10, 10);
    context.closePath();
    ele.attrs.fill = '#fffff7';
    canvas.fillStroke(ele);

    context.beginPath();
    context.rect(x-5, y-5+h/2, 10, 10);
    context.closePath();
    ele.attrs.fill = '#fffff8';
    canvas.fillStroke(ele);

    context.beginPath();
	context.moveTo(x + w/2, y + h/2 - 7);
	context.lineTo(x + w/2, y + h/2 - 30);
    ele.attrs.fill = null;
    ele.attrs.stroke = '#333333';
    ele.attrs.strokeWidth = 1;
    canvas.fillStroke(ele);  

    context.beginPath();
    context.arc(x + w/2, y + h/2 - 30, 6, 0, 2 * Math.PI, false);
    ele.attrs.strokeWidth = 1;
    ele.attrs.fill = '#ffe400';
    canvas.fillStroke(ele);

    if(ele.attrs.name.indexOf('chenhinh')!=-1){
    	imgtemp = tempImg_shape[ele.attrs.name];
    	current_move_shape = imgtemp.current_move_shape;
    	
    	osX = moveImg_shape[current_move_shape].osX;
    	osY = moveImg_shape[current_move_shape].osY;
    	
	    context.beginPath();
	    context.rect(x + w/2 - 5 + osX, y + h/2 + 30 + osY, 10, 10);
	    context.closePath();

	    context.font = 'normal 14px Calibri';
    	context.fillStyle = '#ff0001';
	    context.fillText('DI CHUYỂN', x + w/2 - 25 + osX, y + h/2 + 55 + osY);

	    ele.attrs.fill = '#ff0000';
	    canvas.fillStroke(ele);
	}

    var rotateImg = new Image();
    rotateImg.src = base_url+'img/rotate.png';
    context.beginPath(); 
    context.rect(x + w/2 - 10, y + h/2 - 10, 20, 20);
    context.drawImage(rotateImg, x + w/2 - 10, y + h/2 - 10, 20, 20);
    context.closePath();
    ele.attrs.fill = null;
    ele.attrs.stroke = null;
    ele.attrs.strokeWidth = 0;
    canvas.fillStroke(ele);  
}
function check_drag(){
	var ctx = layer.getContext();
	var get_pixel = ctx.getImageData(mouseSX,mouseSY,1,1);
	if(get_pixel.data[3]==255||get_pixel.data[3]==2||get_pixel.data[3]==3) return true;
	else {
		choose_shape = '';
		return false;
	};
}
function check_resize(){
	var ctx = layer.getContext();
	var get_pixel = ctx.getImageData(mouseSX,mouseSY,1,1);
	resize_shape = -1;
	move_shape = -1;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==241) resize_shape = 1;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==242) resize_shape = 2;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==243) resize_shape = 3;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==244) resize_shape = 4;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==245) resize_shape = 5;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==246) resize_shape = 6;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==247) resize_shape = 7;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==255&&get_pixel.data[2]==248) resize_shape = 8;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==228&&get_pixel.data[2]==0) resize_shape = 9;
	if(get_pixel.data[0]==255&&get_pixel.data[1]==0&&get_pixel.data[2]==0) move_shape = 1;
}
function switch_layer(){
	choose_shape = '';
	layer.draw();
	var ctx = layer.getContext();
	history.push(colorLayerData);
	tempLayerData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
	clearCanvasTransparent();
	context.drawImage(outlineImage, drawingAreaX, drawingAreaY, drawingAreaWidth, drawingAreaHeight);
	colorLayerData = context.getImageData(0, 0, canvasWidth, canvasHeight);
	mergeLayerShape();
	// mergeLayer();
	// mergeLayerKhungTranh();
	context.putImageData(colorLayerData, 0, 0);
	colorLayerData = context.getImageData(0, 0, canvasWidth, canvasHeight);
	layer.remove();
	layer = new Kinetic.Layer();
	stage.add(layer);
	current_shape = -1;
	img_shape = Array();
	$('#canvasDiv2').show();
}
    // Add mouse events
	// ----------------
$('#canvasDiv2').mousedown(function(e)
{	
	e.originalEvent.preventDefault();
	if(toolChoose<=0||mode_shape=='') return;


	mouseDX = mouseSX = mouseX = e.pageX - this.offsetLeft - $('.container')[0].offsetLeft;
	mouseDY = mouseSY = mouseY = e.pageY - this.offsetTop;
	drag_shape = check_drag();

	if(curTool=='shape' && drag_shape==false){
		current_shape++;
		shapeX = mouseX;
		shapeY = mouseY;
	}
	if(drag_shape==false) paint = true;
});

$('#canvasDiv2').mousemove(function(e){
	if(toolChoose<=0) return;
	mouseSX = mouseX = e.pageX - this.offsetLeft - $('.container')[0].offsetLeft;
	mouseSY = mouseY = e.pageY - this.offsetTop;
	
	if(paint==true){
		
		if(curTool=='shape'){
			shapeW = mouseX - shapeX;
			shapeH = mouseY - shapeY;
		}
		drawshape(false);
	}
});

$('#canvasDiv2').mouseup(function(e){
	if(toolChoose<=0) return;
	if(document.body.style.cursor=='default' && !$('.input-text').hasClass('active')){
  		choose_shape = '';
  		layer.draw();
  		paint = false;
  		editing = true;
  		return;
	}
	mouseX = e.pageX - this.offsetLeft - $('.container')[0].offsetLeft;
	mouseY = e.pageY - this.offsetTop;

  	if(drag_shape==false && paint==true && (mouseX!=mouseDX||mouseY!=mouseDY)) drawshape(true);
  	if(mouseX==mouseDX&&mouseY==mouseDY && drag_shape==false) {
  		current_shape--;
  		choose_shape = '';
  		layer.draw();
  	}
	paint = false;
	editing = true;
});

$('#canvasDiv2').dblclick(function(){
	if(!$('.input-text').hasClass('active') && curTool == "nhaptext"){
		reset_choose_shape();
		$('.tt-toolbar .font.active').click();
	}
});

$('#canvasDiv2').mouseleave(function(e){
	if(toolChoose<=0) return;
  	if(drag_shape==false && paint==true && (mouseX!=mouseDX||mouseY!=mouseDY)) drawshape(true);
  	if(mouseX==mouseDX&&mouseY==mouseDY && drag_shape==false) {
  		current_shape--;
  		choose_shape = '';
  		layer.draw();
  	}
	paint = false;
});

$(document).on('keydown',function(e){
	if(e.keyCode==46 && choose_shape!='' && !$('.input-text').hasClass('active')){
		var shape = layer.get('.'+choose_shape)[0];
		shape.remove();
		choose_shape='';
		layer.draw();
	}
});